package com.crayon.account;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.crayon.account.dummy.DummyContent;
import com.crayon.account.fragments.FRGListMain;
import com.crayon.account.fragments.FragmentDailyList;
import com.crayon.account.impl.OnDialogFragment;
import com.crayon.sharemenu.R;
import com.crayon.util.GDB;
import com.crayon.util.UTILSC;
import com.google.ads.AdRequest;
import com.google.ads.AdView;

/**
 *
 */
public class ActivityLeftMenus extends FragmentActivity 
implements
ItemListFragment.Callbacks 
{

	private DrawerLayout mDrawerLayout;
	private View mDrawer;


	private ActionBarHelper mActionBar;
	private ActionBarDrawerToggle mDrawerToggle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_drawer_layout);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerLayout.setDrawerListener(new DemoDrawerListener());
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
		mActionBar = createActionBarHelper();
		mActionBar.init();

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close);
		mDrawer = findViewById(R.id.drawer_layout_left);

		ActionBar bar = getActionBar();
		bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_rect_top_background_green));
		//		bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO);
		//		bar.setDisplayOptions(ActionBar.DISPLAY_USE_LOGO);
		//		ActionBar.
		//		bar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP);
		//		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		bar.setDisplayShowHomeEnabled(true);
		if(savedInstanceState==null){
			FragmentManager fm = getSupportFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();
			try {
				ItemDetailFragment fragment =new FragmentDailyList();
				ft = getSupportFragmentManager().beginTransaction();
				ft.replace(R.id.item_detail_container, fragment);
				ft.commit();
			} catch (Exception e) {
				Log.i("", "@@@ ERR" + e.getMessage() );

			}
		}
		
		adView = (AdView)findViewById(R.id.adView);
	    adView.loadAd(new AdRequest());
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}


	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}


	/**
	 * A drawer listener can be used to respond to drawer events such as becoming
	 * fully opened or closed. You should always prefer to perform expensive operations
	 * such as drastic relayout when no animation is currently in progress, either before
	 * or after the drawer animates.
	 *
	 * When using ActionBarDrawerToggle, all DrawerLayout listener methods should be forwarded
	 * if the ActionBarDrawerToggle is not used as the DrawerLayout listener directly.
	 */
	private class DemoDrawerListener implements DrawerLayout.DrawerListener {
		@Override
		public void onDrawerOpened(View drawerView) {
			mDrawerToggle.onDrawerOpened(drawerView);
			mActionBar.onDrawerOpened();
		}

		@Override
		public void onDrawerClosed(View drawerView) {
			mDrawerToggle.onDrawerClosed(drawerView);
			mActionBar.onDrawerClosed();
		}

		@Override
		public void onDrawerSlide(View drawerView, float slideOffset) {
			mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
		}

		@Override
		public void onDrawerStateChanged(int newState) {
			mDrawerToggle.onDrawerStateChanged(newState);
		}
	}

	/**
	 * Create a compatible helper that will manipulate the action bar if available.
	 */
	private ActionBarHelper createActionBarHelper() {

		//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			return new ActionBarHelperICS();
		} else {
			return new ActionBarHelper();
		}
	}

	/**
	 * Stub action bar helper; this does nothing.
	 */
	private class ActionBarHelper {
		public void init() {}
		public void onDrawerClosed() {}
		public void onDrawerOpened() {}
		public void setTitle(CharSequence title) {}
	}

	/**
	 * Action bar helper for use on ICS and newer devices.
	 */
	private class ActionBarHelperICS extends ActionBarHelper {
		private final ActionBar mActionBar;
		private CharSequence mDrawerTitle;
		private CharSequence mTitle;

		ActionBarHelperICS() {
			mActionBar = getActionBar();
		}

		@Override
		public void init() {
			mActionBar.setDisplayHomeAsUpEnabled(true);
			//			mActionBar.setHomeButtonEnabled(true);
			mTitle = mDrawerTitle = getTitle();
		}

		/**
		 * When the drawer is closed we restore the action bar state reflecting
		 * the specific contents in view.
		 */
		@Override
		public void onDrawerClosed() {
			super.onDrawerClosed();
			mActionBar.setTitle(mTitle);

		}

		/**
		 * When the drawer is open we set the action bar to a generic title.
		 * The action bar should only contain data relevant at the top level of
		 * the nav hierarchy represented by the drawer, as the rest of your content
		 * will be dimmed down and non-interactive.
		 */
		@Override
		public void onDrawerOpened() {
			super.onDrawerOpened();
			mActionBar.setTitle(mDrawerTitle);
		}

		@Override
		public void setTitle(CharSequence title) {
			mTitle = title;
		}
	}

	@Override
	public void onItemSelected(String id) {
		// TODO Auto-generated method stub
		mDrawerLayout.closeDrawer(mDrawer);
		GDB.log(getClass(), "id " + id);
		Bundle arguments = new Bundle();
		arguments.putString(ItemDetailFragment.ARG_ITEM_ID, getIntent()
				.getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
		//			
		DummyContent.DummyItem mItem= DummyContent.ITEM_MAP.get(id);
		mActionBar.setTitle(mItem.toString());
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		try {
			Object fragmentClass =Class.forName(mItem.detailFragment.getName()).newInstance();
			ItemDetailFragment fragment =(ItemDetailFragment) fragmentClass;
			ft = getSupportFragmentManager().beginTransaction();
			fragment.setArguments(arguments);
			ft.replace(R.id.item_detail_container, fragment);
			//	        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			//	        ft.addToBackStack(null);
			ft.commit();
//			Log.i("", "@@@ CRAETE" + fragment.getClass());
		} catch (Exception e) {
//			Log.i("", "@@@ ERR" + e.getMessage() );

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		/*
		 * The action bar home/up action should open or close the drawer.
		 * mDrawerToggle will take care of this.
		 */
		GDB.log(getClass(), ">>>onOptionsItemSelected " + item.getItemId());
		switch (item.getItemId()) {
			case R.id.camera:
				Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.item_detail_container);
				if(fragment instanceof OnDialogFragment){
					UTILSC.addOnPopWriteFragment((FragmentActivity)this, null, (OnDialogFragment)fragment);
				}else{
					UTILSC.addOnPopWriteFragment((FragmentActivity)this, null, null);
				}
				return true;
		}

		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub

		String msg = String.format("%d ", getSupportFragmentManager().getBackStackEntryCount());
		GDB.log(getClass(), msg );
		if(getSupportFragmentManager().getBackStackEntryCount()>0) super.onBackPressed();
		else{
			String message = String.format("%s %s", getString(R.string.app_name),getString(R.string.app_message_appclise));
			new AlertDialog.Builder(this).setMessage(message)
			.setNegativeButton(android.R.string.cancel, new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			}).setPositiveButton(android.R.string.ok, new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					finish();

				}
			})

			.create()

			.show();
		}

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
//		GDB.log(getClass(), "FUCK ActivityResult");
	}

	private AdView adView;
    @Override
    public void onDestroy() {
        super.onDestroy();
        try{
            if(adView!=null)adView.destroy();

        }catch (Exception e){

        }
    }
}

